package com.fay.mymiaosha.controller;

import com.fay.mymiaosha.controller.vo.ItemVO;
import com.fay.mymiaosha.exception.BizException;
import com.fay.mymiaosha.response.CommonReturnType;
import com.fay.mymiaosha.service.IItemService;
import com.fay.mymiaosha.service.model.ItemModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/3/17 20:42
 * @Version 1.0
 */
@RestController("item")
@RequestMapping("/item")
public class ItemController extends BaseController {

    @Autowired
    private IItemService itemService;

    // 管理人员后台使用
    @RequestMapping(value = "/create", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
    public CommonReturnType createItem(@RequestParam(name = "title") String title,
                                       @RequestParam(name = "description") String description,
                                       @RequestParam(name = "price") BigDecimal price,
                                       @RequestParam(name = "stock") Integer stock,
                                       @RequestParam(name = "imgUrl") String imgUrl) throws BizException {

        //create model and let service handle
        ItemModel itemModel = new ItemModel();
        itemModel.setTitle(title);
        itemModel.setDescription(description);
        itemModel.setPrice(price);
        itemModel.setStock(stock);
        itemModel.setImgUrl(imgUrl);

        // create and find for return
        ItemModel itemModelForReturn = itemService.createItem(itemModel);

        // give to front end in json type
        return CommonReturnType.create(itemModelForReturn);

    }

    // 查  查所有  和  查一个  （纲目）

    // 用户，查看所有的商品列表
    @GetMapping("/list")
    public CommonReturnType listItems() {
        List<ItemModel> itemList = itemService.listItems();
        List<ItemVO> itemVOList = itemList.stream().map(this::convertFromItemModel).collect(Collectors.toList());
        return CommonReturnType.create(itemVOList);
    }

    // 用户，查看详细商品信息
    @GetMapping("/get")
    public CommonReturnType getItem(@RequestParam(name = "id") Integer id) {
        ItemModel itemModel = itemService.getItemById(id);
        ItemVO itemVO = convertFromItemModel(itemModel);
        return CommonReturnType.create(itemVO);
    }

    // 商品的购买行为不应该在商品行为中，而是在交易模型中。
    // 转换
    private ItemVO convertFromItemModel(ItemModel itemModel) {
        if (itemModel == null) {
            return null;
        }
        ItemVO itemVO = new ItemVO();
        BeanUtils.copyProperties(itemModel, itemVO);
        return itemVO;
    }


}
